from django.shortcuts import render, get_object_or_404
from .models import Post,Category,Tag
from comments.forms import CommentForm
from django.views.generic import ListView

import markdown
from markdown_checklist.extension import ChecklistExtension

def index(request):
	post_list = Post.objects.all().order_by('category','-created_time')
	return render(request, 'blog/index.html', context={'post_list': post_list})

def detail(request, pk):
	post = get_object_or_404(Post, pk=pk)
	post.increase_views()
	md = markdown.Markdown(extensions=[
		'markdown.extensions.extra',
		'markdown.extensions.codehilite',
		'markdown.extensions.toc',
		'markdown_checklist.extension',
		])
	post.body = md.convert(post.body)
	post.toc = md.toc
	# 记得在顶部导入 CommentForm
	form = CommentForm()
	# 获取这篇 post 下的全部评论
	comment_list = post.comment_set.all()

	# 将文章、表单、以及文章下的评论列表作为模板变量传给 detail.html 模板，以便渲染相应数据。
	context = {'post': post,
				'form': form,
				'comment_list': comment_list
	}
	return render(request, 'blog/detail.html', context=context)

def archives(request, year, month):
	post_list = Post.objects.filter(
		created_time__year = year,
		created_time__month = month,
		).order_by('-created_time')
	return render(request, 'blog/index.html', context={'post_list': post_list})

def category(request, pk):
	cate = get_object_or_404(Category, pk=pk)
	post_list = Post.objects.filter(category=cate).order_by('-created_time')
	return render(request, 'blog/index.html', context={'post_list': post_list})

def tag(request, pk):
	tags = get_object_or_404(Tag, pk=pk)
	post_list = Post.objects.filter(tags=tags).order_by('-created_time')
	return render(request, 'blog/index.html', context={'post_list': post_list})


def person(request, pk, name = 'Cihon'):
	post_list = Post.objects.filter(
		author__pk = pk
	).order_by('-created_time')
	return render(request, 'blog/index.html', 
		context={'post_list': post_list,
				'name':name})
	
def tree(request):
	return render(request, 'tree/tree.html')

def summer(request):
	return person(request,1,'summer')


def magic(request):
	return person(request,5,'magic')


def zengjia(request):
	return person(request,6,'zengjia')


def yaojie(request):
	return person(request,7,'yaojie')

def bubble(request):
	return render(request, 'blog/bubble.html')